package org.sippr.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

public class ImgUtil {
    public static BufferedImage processBase64Image(String base64Image) throws IOException {
        byte[] decodedBytes = Base64.getDecoder().decode(base64Image);

        // 将字节数组转换为输入流
        ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);

        // 使用ImageIO读取输入流中的图像数据
        BufferedImage image = ImageIO.read(bis);

        // 可以对图像进行进一步的处理，如缩放、裁剪、旋转等

        // 在这里打印或处理图像
//        System.out.println("Image width: " + image.getWidth());
//        System.out.println("Image height: " + image.getHeight());

        // 关闭输入流
        bis.close();
        return image;
    }


    public static String imgToBase64(String path) {

        try {
            // 读取图片文件
            File file = new File(path);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] imageData = new byte[(int) file.length()];
            inputStream.read(imageData);
            inputStream.close();

            // 将图片数据编码为Base64字符串
            String base64Image = Base64.getEncoder().encodeToString(imageData);

            return base64Image;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void saveImage(BufferedImage image, String filePath) {
        try {
            // 将 BufferedImage 写入到指定的文件中
            File output = new File(filePath);
            ImageIO.write(image, "png", output);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
